import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/address_entity.dart';
import 'package:panda/entity/article_list_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/set/ArticleDetail.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/SignUtil.dart';
import '../base/Constant.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import '../base/Constant.dart';
import '../base/Constant.dart';

class StudyClassPage extends StatefulWidget {
  int type = 0;
  StudyClassPage({Key key, this.type}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return StudyClassView();
  }
}

class StudyClassView extends State<StudyClassPage> {
  List<HomeListDataData> dataList = new List();
  int page = 1;
  String token = "";
  EasyRefreshController _controller = EasyRefreshController();
  // List<VideoPlayerController> list = new List();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      // loadList();
    });
    loadList();
  }

  @override
  void dispose() {
    // for (int i = 0; i < list.length; i++) {
    //   list[i].pause();
    //   list[i].dispose();
    // }
    super.dispose();
  }

  loadList() async {
    // for (int i = 0; i < list.length; i++) {
    //   list[i].pause();
    // }
    Map map = new Map();
    map['cat_id'] = "6";
    map['p'] = page.toString();
    map['per'] = "10";
    map['sign_type'] = SignType.GET_ARTICLE_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_SYSTEM_ARTICLE, data: getSign(map));
    print(response.data);
    Map userMap = json.decode(response.data);
    HomeListEntity homeServiceEntity = new HomeListEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      if (page == 1) {
        dataList.clear();
        // list.clear();
        _controller.resetLoadState();
        _controller.finishRefresh();
      } else {
        _controller.finishLoad(
            noMore: homeServiceEntity.data.datas.length == 0);
        if (homeServiceEntity.data.datas.length == 0) {
          Fluttertoast.showToast(msg: "已经加载全部");
        }
      }
      dataList.addAll(homeServiceEntity.data.datas);
      // for (int i = 0; i < homeServiceEntity.data.datas.length; i++) {
      //   // VideoPlayerController controller = VideoPlayerController.path(
      //   //     homeServiceEntity.data.datas[i].href.toString())
      //   //   ..initialize();
      //   // list.add(controller);
      // }
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text('学堂',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: new Container(
        color: white,
        child: new EasyRefresh(
          enableControlFinishRefresh: true,
          enableControlFinishLoad: true,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          controller: _controller,
          child: ListView.builder(
              itemBuilder: _renderRow, itemCount: dataList.length),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          },
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setHeight(DP_20),
          ScreenUtil.getInstance().setHeight(DP_20),
          ScreenUtil.getInstance().setHeight(DP_20),
          0),
      decoration: BoxDecoration(
          color: white,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10))),
      child: Material(
        borderRadius:
            BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10)),
        color: white,
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.only(
                  topRight: Radius.circular(
                      ScreenUtil.getInstance().setHeight(DP_10)),
                  topLeft: Radius.circular(
                      ScreenUtil.getInstance().setHeight(DP_10))),
              child: dataList[index].img == ""
                  ?Image.asset('images/app_icon.png',
                      width: MediaQuery.of(context).size.width -
                          ScreenUtil.getInstance().setHeight(DP_40),
                      fit: BoxFit.fill,
                      height: (MediaQuery.of(context).size.width -
                              ScreenUtil.getInstance().setHeight(DP_40)) /
                          2): CachedNetworkImage(
                imageUrl:Api.ImgBaseUrl + dataList[index].img,
                      width: MediaQuery.of(context).size.width -
                          ScreenUtil.getInstance().setHeight(DP_40),
                      fit: BoxFit.fill,
                      height: (MediaQuery.of(context).size.width -
                              ScreenUtil.getInstance().setHeight(DP_40)) /
                          2),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_8)),
              child: Text(
                dataList[index].title,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                    color: black),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_15),
                  0,
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15)),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Text('金牌讲师：' + dataList[index].author,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                          color: mainColor)),
                ],
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_15),
                  0,
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15)),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    width: 18 * 4.toDouble() + 12,
                    child: Stack(
                      alignment: AlignmentDirectional.topStart,
                      children: <Widget>[
                        ClipOval(
                          child: CachedNetworkImage(
                imageUrl:
                              'https://cdn2.jianshu.io/assets/default_avatar/14-0651acff782e7a18653d7530d6b27661.jpg',
                              width: 30,
                              height: 30),
                        ),
                        Positioned(
                          left: 18,
                          child: ClipOval(
                            child: CachedNetworkImage(
                imageUrl:
                                'https://cdn2.jianshu.io/assets/default_avatar/14-0651acff782e7a18653d7530d6b27661.jpg',
                                width: 30,
                                height: 30),
                          ),
                        ),
                        Positioned(
                          left: 36,
                          child: ClipOval(
                            child: CachedNetworkImage(
                imageUrl:
                                'https://cdn2.jianshu.io/assets/default_avatar/14-0651acff782e7a18653d7530d6b27661.jpg',
                                width: 30,
                                height: 30),
                          ),
                        ),
                        Positioned(
                          left: 54,
                          child: ClipOval(
                            child: CachedNetworkImage(
                imageUrl:
                                'https://cdn2.jianshu.io/assets/default_avatar/14-0651acff782e7a18653d7530d6b27661.jpg',
                                width: 30,
                                height: 30),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(width: ScreenUtil.getInstance().setHeight(DP_15)),
                  Text(dataList[index].clicknum + '人已学',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(MINI_FONT_SIZE),
                          color: Colors.black45)),
                  Expanded(
                    child: Center(),
                  ),
                  new Container(
                    height: ScreenUtil.getInstance().setWidth(DP_50),
                    decoration: new BoxDecoration(
                        border: Border.all(color: mainColor, width: 1),
                        borderRadius: BorderRadius.circular(2)),
                    child: new FlatButton(
                      child: new Padding(
                        padding: EdgeInsets.all(0.0),
                        child: new Text(
                          "去学习",
                          style: new TextStyle(
                              color: mainColor,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                      ),
                      onPressed: () {
                        Navigator.of(context)
                            .push(MaterialPageRoute(builder: (context) {
                          return new ArticleDetailPage(
                            article_id: dataList[index].article_id,
                          );
                        }));
                      },
                    ),
                  )
                ],
              ),
            )
          ],
        ),
        elevation: 1,
      ),
    );
  }
}
